package com.css.crm.bean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;

import com.css.crm.exception.SystemException;
import com.css.crm.message.SystemErrorMessage;
import com.css.crm.message.SystemMessage;
import com.css.crm.utility.ConstantUtil;
import com.css.crm.utility.DateUtil;
import com.css.crm.utility.SystemUtil;
import com.css.crm.vo.AbstractUser;
import com.css.crm.vo.CustomerAddressVo;
import com.css.crm.vo.CustomerEmailVo;
import com.css.crm.vo.CustomerTelephoneVo;
import com.css.crm.vo.CustomerVo;
import com.css.db.MyBatisConfig;

/**
 * For create customer function
 * 
 * @author AIS
 * 
 */
@ManagedBean(name = "createCustomerBean")
@SessionScoped
public class CreateCustomerBean extends CustomerBean {

	public CreateCustomerBean() {
		super();

		toAddCustomer(null);

	}

	/**
	 * to crate a customer
	 * 
	 * @param event
	 */
	public void toAddCustomer(ActionEvent event) {
		activeTab = "customerTabInfoId";
		customer = new CustomerVo();

		// default customer status valid
		customer.setStatCde(ConstantUtil.CUSTOMER_STAT_CODE_V);

		// default empty telephone record
		List<CustomerTelephoneVo> customerTelephoneList = new ArrayList<CustomerTelephoneVo>();
		customerTelephoneList.add(new CustomerTelephoneVo());
		customer.setCustomerTelephoneList(customerTelephoneList);

		// default empty email record
		List<CustomerEmailVo> customerEmailList = new ArrayList<CustomerEmailVo>();
		customerEmailList.add(new CustomerEmailVo());
		customer.setCustomerEmailList(customerEmailList);

		// default empty address record
		List<CustomerAddressVo> customerAddressList = new ArrayList<CustomerAddressVo>();
		CustomerAddressVo addressVo = new CustomerAddressVo();
		addressVo.initItems();
		customerAddressList.add(addressVo);
		customer.setCustomerAddressList(customerAddressList);

	}

	/**
	 * create or update single customer
	 * 
	 * @param event
	 */
	public void saveCustomer(ActionEvent event) {

		log.info("start save customer");

		SqlSession session = MyBatisConfig.getSession();
		customerService.setSession(session);

		boolean validateResult = customerService.validateCustomer(customer);
		if (!validateResult) {
			return;
		}

		try {
			if (StringUtils.isNotEmpty(customer.getTitle())) {
				if (ConstantUtil.CUSTOMER_TITLE_MR.equals(customer.getTitle())) {
					customer.setSex(ConstantUtil.CUSTOMER_SEX_MALE);
				} else {
					customer.setSex(ConstantUtil.CUSTOMER_SEX_FEMALE);
				}
			}

			if (StringUtils.isEmpty(this.customer.getCustId())) {
				// user system service to get original country code
				systemService.setSession(session);

				log.info("add customer.");
				// create customer
				saveAddCustomer();
				log.info("end add customer.");

				log.info("create solr document.");
				// solr index for new customer
				solrService.createDocument(customer);
				log.info("end create solr document.");

			}

			session.commit();
			SystemUtil.addMessage(SystemMessage.SYSTEM_SAVE_SUCCEED.getSystemMessage());

			toAddCustomer(event);

		} catch (SystemException e) {
			SystemUtil.addMessageError(e.getNewSystemMessage());
			log.error(e.getMessage());
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

	private void saveAddCustomer() throws SystemException {
		AbstractUser user = (AbstractUser) SystemUtil.getSession(ConstantUtil.SESSION_USER_KEY);
		Long origCtryCode = systemService.getOrigCtryCode(user.getDepartmentCode());
		if (origCtryCode == null) {
			throw new SystemException(SystemErrorMessage.UNEXPECTED_EXCEPTION);
		}
		customer.setAcctNam("");
		customer.setMbrClass(ConstantUtil.CUSTOMER_MBR_CLASS_I);
		customer.setOrigCtryCde(origCtryCode);
		// customer.setStatCde(ConstantUtil.CUSTOMER_STAT_CODE_V);
		customer.setCrtDeptCde(user.getDepartmentCode());
		customer.setCrtDte(new Date());
		customer.setLastModDte(new Date());
		customer.setLastModUser(user.getSmUserId());
		customer.setJoinDeptCde(user.getDepartmentCode());

		String custId = customerService.getNextCustId(origCtryCode);
		customer.setCustId(custId);

		if (StringUtils.isNotEmpty(customer.getDobMonth()) && StringUtils.isNotEmpty(customer.getDobDay())) {
			customer.setDob(DateUtil.parseDate(ConstantUtil.DEFAULT_YEAR_DOB + "-" + customer.getDobMonth() + "-" + customer.getDobDay()));
		}
		customerService.createCustomer(customer);
	}

	public void cancelCustomer(ActionEvent event) {
		toAddCustomer(event);
		clearPageData();
	}

}
